<?php

namespace addons\upyun;

use think\Addons;
use think\Loader;
use Upyun\Config;
use Upyun\Signature;
use Upyun\Upyun as UpyunClient;
use Upyun\Util;

/**
 * 又拍云上传
 */
class Upyun extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        return true;
    }

    /**
     * 添加命名空间
     */
    public function appInit()
    {
        if (!class_exists('\Upyun\Upyun')) {
            //添加支付包的命名空间
            Loader::addNamespace('Upyun', ADDON_PATH . 'upyun' . DS . 'library' . DS . 'Upyun' . DS);
        }
    }

    /**
     *
     * @return mixed
     */
    public function uploadConfigInit(&$upload)
    {
        $config = $this->getConfig('upyun');
        $config = $config ? $config : [];
        $config['bucket'] = isset($config['bucket']) ? $config['bucket'] : '';
        $multiple = isset($config['multiple']) ? $config['multiple'] : false;

        $params = [];
        $params['save-key'] = isset($config['savekey']) ? $config['savekey'] : '';
        $params['bucket'] = $config['bucket'];
        $params['expiration'] = time() + (isset($config['expire']) ? $config['expire'] : 600);

        $cfg = new Config($config['bucket'], $config['operator'], $config['password']);
        $policy = Util::base64Json($params);
        $signature = Signature::getBodySignature($cfg, 'POST', '/' . $params['bucket'], null, $policy);
        $upyuntoken = base64_encode($signature) . ":" . $policy;
        $multipart = [
            'upyuntoken' => $upyuntoken,
        ];

        $upload = array_merge($upload, [
            'cdnurl'     => $config['cdnurl'],
            'uploadurl'  => $config['uploadmode'] == 'client' ? $config['uploadurl'] : addon_url('upyun/index/upload'),
            'uploadmode' => $config['uploadmode'],
            'bucket'     => $config['bucket'],
            'maxsize'    => $config['maxsize'],
            'mimetype'   => $config['mimetype'],
            'savekey'    => $config['savekey'],
            'chunking'   => (bool)($config['chunking'] ?? $upload['chunking']),
            'chunksize'  => (int)($config['chunksize'] ?? $upload['chunksize']),
            'multipart'  => ['upyuntoken' => $upyuntoken],
            'storage'    => $this->getName(),
            'multiple'   => $config['multiple'] ? true : false,
        ]);
    }

    /**
     * 附件删除后
     */
    public function uploadDelete($attachment)
    {
        $config = $this->getConfig();
        if ($attachment['storage'] == 'upyun' && isset($config['syncdelete']) && $config['syncdelete']) {
            $cfg = new \Upyun\Config($config['bucket'], $config['operator'], $config['password']);
            $upyun = new UpyunClient($cfg);
            //同步删除又拍云文件
            $ret = $upyun->delete($attachment->url);
            //如果是服务端中转，还需要删除本地文件
            if ($config['uploadmode'] == 'server') {
                $filePath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url);
                if ($filePath) {
                    @unlink($filePath);
                }
            }
        }
        return true;
    }
}
